<template>
	<div v-loading="loading" class="home-view">
		<el-button class="download" type="text" @click="downloadChart" :icon="Download">下载图片</el-button>
		<download-excel class="export" :data="excelData" :fields="jsonFields" :name="fileName">
			<el-button type="text" :icon="Document">导出excel</el-button>
		</download-excel>

		<div class="echart" ref="echartContainer"></div>
	</div>
</template>

<script lang='ts' setup>
import { Download, Document } from '@element-plus/icons-vue'
import { onMounted, ref, shallowRef, watch } from 'vue';
import { useRoute } from 'vue-router';
import API from '../api/home';
import * as echarts from 'echarts';
import dayjs from 'dayjs';

const loading = ref(false);
const route = useRoute();
let echartContainer = ref(null);
let echart = shallowRef();
const source = ref<string[]>([]);
let fileName = ref<string>('');

let excelData = ref<any[]>([]);

let jsonFields = ref({
	站点: 'station',
	数据源: 'source',
	起报时间: 'queryTime',
	数据日期: 'day',
	最大值: 'maxVal',
	最小值: 'minVal',
	平均值: 'avgVal'
});

type Source = {
    [key: string]: string,
}
const SOURCE: Source  = {
	ecjh: '集合预报',
	ecnc: 'EC',
	nwgd: '国家指导',
	ots: 'OTS',
	daf: 'T-DAF',
	ysq: '滑动气温',
};

const arr = [
	{id: 'ecjh', name: '集合预报',maxVal: '#0070C0', minVal: '#0070C0', avgVal: '#0070C0'},
	{id: 'ecnc', name: 'EC',maxVal: '#FF8080', minVal: '#FF8080', avgVal: '#FF8080'},
	{id: 'nwgd', name: '国家指导',maxVal: '#FF0080', minVal: '#FF0080', avgVal: '#FF0080'},
	{id: 'ots', name: 'OTS',maxVal: '#008080', minVal: '#008080', avgVal: '#008080'},
	{id: 'daf', name: 'T-DAF',maxVal: '#8080FF', minVal: '#8080FF', avgVal: '#8080FF'},
	{id: 'ysq', name: '滑动气温',maxVal: '#8080FF', minVal: '#8080FF', avgVal: '#8080FF'}
];

type Element = {
    [key: string]: string,
}
const ELEMENT: Element  = {
	maxVal: '最高气温',
	minVal: '最低气温',
	avgVal: '平均气温',
	allVal: '综合分析'
};

const COLOR: Element  = {
	maxVal: '#3C91CF',
	minVal: '#FF0A0A',
	avgVal: '#7F7F7F'
};

interface DataList {
    date: string;
    value: number;
}

interface ResponseData {
    dafList: DataList[];
    otsList: DataList[];
    ecjhList: DataList[];
    ecncList: DataList[];
    nwgdList: DataList[];
}

interface CountDayTmpDataList {
    day: string;
    maxVal: number;
    minVal: number;
    avgVal: number;
}

watch(() => route.query.element, (newVal, oldVal) => {
	console.log('watch element======>', newVal);
	selectCountTmpOrCountDayTmp();
});

watch(() => route.query.queryTime, (newVal, oldVal) => {
	console.log('watch queryTime======>', newVal);
	selectCountTmpOrCountDayTmp();
});


watch(() => route.query.lon, (newVal, oldVal) => {
	console.log('watch lon======>', newVal);
	selectCountTmpOrCountDayTmp();
});

watch(() => route.query.source, (newVal, oldVal) => {
	console.log('watch source======>', newVal);
	selectCountTmpOrCountDayTmp();
});

onMounted(() => {
	console.log('onMounted====>123');
    // countDayTmp();
	selectCountTmpOrCountDayTmp();
})

const selectCountTmpOrCountDayTmp = () => {
	let { element, queryTime, source, lon } = route.query;
	if (!element || !queryTime || !source || !lon) return;
	if (element === 'TMP') {
		countTmp();
	} else {
		countDayTmp();
	}
}

const countTmp = async () => {
	if (echart.value && echart.value.dispose) {
		echart.value.dispose();
	}
	echart.value = echarts.init(echartContainer.value);
	try {
		loading.value = true;
		let res: { data: { data: ResponseData, code: number } } = await API.countTmp({
			element: 'TMP',
			queryTime: route.query.queryTime,
			lon: route.query.lon,
			lat: route.query.lat,
		});
		let { data, code } = res.data;
		if (code === 200) {
			let legendData: string[] = [];
			let series: Array<{}> = [];
			source.value = (route.query.source as string).split(',');
			source.value.forEach(el => {
				legendData.push(SOURCE[el]);
				let obj = {
					name: SOURCE[el],
					type: ['ecjh', 'ecnc'].includes(el) ? 'bar' : 'line',
					smooth: true,
					data: ((data as any)[`${el}List`] as DataList[]).map(item => item.value),
					label: {
						show: true
					}
				};
				series.push(obj);
			});
			console.log('series======>', series);
			let xAxisData = data.ecjhList.map(el => dayjs(el.date, 'YYYYMMDDHH0000').format('DD日HH时'));
			let option = {
				title: {
					text: '会商供暖'
				},
				tooltip: {
					trigger: 'axis'
				},
				legend: {
					data: legendData,
					selectedMode: false // 禁用图例点击交互
				},
				grid: {
					left: '3%',
					right: '4%',
					bottom: 80,
					containLabel: true
				},
				toolbox: {
					feature: {
						saveAsImage: {}
					}
				},
				dataZoom: [
					{
						show: true,
						realtime: true,
						start: 0,
						end: 10
					},
					{
						type: 'inside',
						realtime: true,
						start: 0,
						end: 10
					}
				],
				xAxis: {
					type: 'category',
					boundaryGap: false,
					data: xAxisData
				},
				yAxis: {
					type: 'value'
				},
				series: series
			};
			echart.value.setOption(option);
		} else {
			ElMessage.error('暂无数据');
		}
	} catch (error) {
		console.error(error);
	} finally {
		loading.value = false;
	}
}

const countDayTmp = async () => {
	let { element, source, queryTime, lon, lat, station } = route.query;
	// element = 'maxVal';
	// source = 'ecnc,nwgd'
	if (echart.value && echart.value.dispose) {
		echart.value.dispose();
	}
	echart.value = echarts.init(echartContainer.value);
	try {
		loading.value = true;
		let sourceArr = (source as string).split(',');
		let res = await API.countDayTmp({
			modeType: sourceArr.join(),
			queryTime: queryTime,
			lon: lon,
			lat: lat
		});
		// let res = await Promise.resolve({data: {"code":200,"msg":"操作成功","data":[{"maxVal":3.5,"minVal":-3.5,"avgVal":-0.2,"day":"20250217"},{"maxVal":3.7,"minVal":-5.0,"avgVal":-1.6,"day":"20250218"},{"maxVal":3.9,"minVal":-5.9,"avgVal":-1.6,"day":"20250219"},{"maxVal":3.2,"minVal":-4.4,"avgVal":-2.2,"day":"20250220"},{"maxVal":2.7,"minVal":-5.3,"avgVal":-2.2,"day":"20250221"},{"maxVal":2.3,"minVal":-5.3,"avgVal":-2.2,"day":"20250222"},{"maxVal":5.0,"minVal":-4.3,"avgVal":-1.2,"day":"20250223"},{"maxVal":6.3,"minVal":-2.9,"avgVal":0.6,"day":"20250224"},{"maxVal":8.4,"minVal":-2.5,"avgVal":2.0,"day":"20250225"},{"maxVal":5.2,"minVal":-3.2,"avgVal":-0.3,"day":"20250226"},{"maxVal":-3.3,"minVal":-3.3,"avgVal":-3.3,"day":"20250227"}]}});
		// let res = await Promise.resolve({data: {"code":200,"msg":"操作成功","data":{"ecnc":[{"maxVal":-2.0,"minVal":-3.8,"avgVal":-2.9,"day":"20250217"},{"maxVal":3.9,"minVal":-4.9,"avgVal":-1.4,"day":"20250218"},{"maxVal":4.2,"minVal":-5.3,"avgVal":-1.5,"day":"20250219"},{"maxVal":2.9,"minVal":-4.1,"avgVal":-1.3,"day":"20250220"},{"maxVal":2.3,"minVal":-4.3,"avgVal":-2.0,"day":"20250221"},{"maxVal":2.3,"minVal":-5.2,"avgVal":-2.1,"day":"20250222"},{"maxVal":4.3,"minVal":-4.9,"avgVal":-1.6,"day":"20250223"},{"maxVal":7.1,"minVal":-3.6,"avgVal":0.3,"day":"20250224"},{"maxVal":7.6,"minVal":-1.7,"avgVal":1.3,"day":"20250225"},{"maxVal":8.1,"minVal":-3.5,"avgVal":0.7,"day":"20250226"},{"maxVal":5.1,"minVal":-0.6,"avgVal":1.5,"day":"20250227"}]}}});
		// let res = await Promise.resolve({data: {"code":200,"msg":"操作成功","data":{"nwgd":[{"maxVal":2.1,"minVal":-0.6,"avgVal":0.8,"day":"20250217"},{"maxVal":4.7,"minVal":-5.0,"avgVal":-0.8,"day":"20250218"},{"maxVal":5.2,"minVal":-6.0,"avgVal":-1.2,"day":"20250219"},{"maxVal":4.3,"minVal":-4.8,"avgVal":-1.1,"day":"20250220"},{"maxVal":3.0,"minVal":-8.2,"avgVal":-3.1,"day":"20250221"},{"maxVal":3.5,"minVal":-7.3,"avgVal":-2.2,"day":"20250222"},{"maxVal":2.5,"minVal":-10.1,"avgVal":-3.5,"day":"20250223"},{"maxVal":4.4,"minVal":-5.6,"avgVal":-0.9,"day":"20250224"},{"maxVal":6.7,"minVal":-1.9,"avgVal":1.1,"day":"20250225"},{"maxVal":10.1,"minVal":-1.1,"avgVal":4.5,"day":"20250226"},{"maxVal":7.2,"minVal":-3.7,"avgVal":1.1,"day":"20250227"}],"ecnc":[{"maxVal":-2.0,"minVal":-3.8,"avgVal":-2.9,"day":"20250217"},{"maxVal":3.9,"minVal":-4.9,"avgVal":-1.4,"day":"20250218"},{"maxVal":4.2,"minVal":-5.3,"avgVal":-1.5,"day":"20250219"},{"maxVal":2.9,"minVal":-4.1,"avgVal":-1.3,"day":"20250220"},{"maxVal":2.3,"minVal":-4.3,"avgVal":-2.0,"day":"20250221"},{"maxVal":2.3,"minVal":-5.2,"avgVal":-2.1,"day":"20250222"},{"maxVal":4.3,"minVal":-4.9,"avgVal":-1.6,"day":"20250223"},{"maxVal":7.1,"minVal":-3.6,"avgVal":0.3,"day":"20250224"},{"maxVal":7.6,"minVal":-1.7,"avgVal":1.3,"day":"20250225"},{"maxVal":8.1,"minVal":-3.5,"avgVal":0.7,"day":"20250226"},{"maxVal":5.1,"minVal":-0.6,"avgVal":1.5,"day":"20250227"}]}}})
		let { data, code } = res.data;
		if (code === 200) {
			let legendData: string[] = [];
			let series: Array<{}> = [];
			for (let key in data) {
				data[key].forEach(el => {
					excelData.value.push({
						station,
						queryTime: dayjs(queryTime as string, 'YYYYMMDDHH0000').format('YYYY-MM-DD HH:00:00'),
						day: dayjs(el.day, 'YYYYMMDD').format('YYYY-MM-DD'),
						source: sourceArr.map(el => SOURCE[el]).join('、'),
						maxVal: el.maxVal,
						minVal: el.minVal,
						avgVal: el.avgVal
					});
				});
				fileName.value = `供暖分析${queryTime}.xlsx`;
				
				if (element === 'maxVal,minVal,avgVal') {
					let ele = (element as string).split(',');
					ele.forEach(el => {
						legendData.push(ELEMENT[el]);
						let dataArr = (data as any)[key].map((item: CountDayTmpDataList) => item[el]);
						let min = Math.round(Math.min(...dataArr) / 5) * 5 - 5;
						let max = Math.round(Math.max(...dataArr) / 5) * 5 + 5;
						let markLineData = [];
						for (let i = min; i <= max; i += 5) {
							markLineData.push({
								label: {
									show: false
								},
								symbolSize: [15, 15],
								lineStyle: {
									type: 'dashed',
									width: 3,
									opacity: 0.5,
									color: '#C8BA91',
								},
								yAxis: i
							});
						}
						let obj = {
							name: ELEMENT[el],
							type: 'line',
							smooth: true,
							data: dataArr,
							label: {
								show: true,
								fontSize: 20,
								fontWeight: 700,
								color: COLOR[el]
							},
							symbolSize: 10,
							itemStyle: {
								color: COLOR[el],
							},
							lineStyle: {
								width: 4
							},
							markLine: {
								symbol: ['circle'],
								silent: true,
								data: markLineData
							},
						};
						series.push(obj);
					});
				} else {
					let item = arr.find(el => el.id === key);
					legendData.push(item.name);
					let dataArr = (data as any)[key].map((el: CountDayTmpDataList) => el[element]);
					let min = Math.round(Math.min(...dataArr) / 5) * 5 - 5;
					let max = Math.round(Math.max(...dataArr) / 5) * 5 + 5;
					let markLineData = [];
					for (let i = min; i <= max; i += 5) {
						markLineData.push({
							label: {
								show: false
							},
							symbolSize: [15, 15],
							lineStyle: {
								type: 'dashed',
								width: 3,
								opacity: 0.5,
								color: '#C8BA91',
							},
							yAxis: i
						});
					}
					let obj = {
						name: item.name || '',
						type: 'line',
						smooth: true,
						data: dataArr,
						label: {
							show: true,
							fontSize: 20,
							fontWeight: 700,
							color: item[element] || ''
						},
						symbolSize: 10,
						itemStyle: {
							color: item[element] || '',
						},
						lineStyle: {
							width: 4
						},
						markLine: {
							symbol: ['circle'],
							silent: true,
							data: markLineData
						},
					};
					series.push(obj);
				}
			}
			console.log('series======>', series);
			let xAxisData = (data as any)[sourceArr[0]].map((el: CountDayTmpDataList) => dayjs(el.day, 'YYYYMMDD').format('DD日'));

			let option = {
				title: {
					text: '气温',
					textStyle: {
						fontSize: 24,
						fontWeight: 700,
						fontFamily: '黑体',
						color: '#000000'
					}
				},
				tooltip: {
					trigger: 'axis'
				},
				legend: {
					data: legendData,
					selectedMode: false, // 禁用图例点击交互
					top: 80,
					left: 150,
					textStyle: {
						fontSize: 24,
						fontWeight: 700,
						fontFamily: '黑体',
						color: '#000000'
					},
					lineStyle: {
						width: 4
					}
				},
				grid: {
					show: true,
					left: '3%',
					right: '4%',
					bottom: 80,
					containLabel: true,
					borderWidth: 2, // 边框宽度
        			borderColor: '#D2A000' // 边框颜色
				},
				graphic: [
					{
						type:'text',
						top: 10,
						right: 100,
						style: {
							text: station,
							font: '700 24px 黑体',
							fill: '#FF0A0A'
						},
					},
					{
						type:'text',
						bottom: 50,
						left: '50%',
						style: {
							text: '日期',
							font: '700 24px 黑体',
							fill: '#000000'
						},
					}
				],
				dataZoom: [
					{
						show: true,
						realtime: true,
						start: 0,
						end: 100
					},
					{
						type: 'inside',
						realtime: true,
						start: 0,
						end: 100
					}
				],
				xAxis: {
					type: 'category',
					boundaryGap: false,
					data: xAxisData,
					axisLabel: {
						show: true,
						fontSize: 20,
						fontWeight: 700,
						fontFamily: '黑体',
						color: '#000000'
					},
					axisLine: {
						show: true,
						lineStyle: {
							width: 3,
							color: '#D2A000' // X 轴线的颜色
						}
					},
					axisTick: {
						show: true,
						length: 8,
						inside: true,
						lineStyle: {
							color: '#D2A000', // 刻度线的颜色
							width: 3, // 刻度线的粗细，这里设置为2，你可以根据需要调整这个值
							
						}
					}
				},
				yAxis: {
					type: 'value',
					axisLabel: {
						show: true,
						margin: 25,
						fontSize: 20,
						fontWeight: 700,
						color: '#000000',
						fontFamily: '黑体',
						formatter: '{value}℃'
					},
					splitNumber: 5,
					// splitLine: {
					// 	lineStyle: {
					// 		color: ['#C8BA91'],
					// 		type: 'dashed',
					// 		width: 3,
					// 		opacity: 0.8
					// 	}
					// },
					min: function (value) {
						return Math.round(value.min / 5) * 5 - 5;
					},
					max: function (value) {
						return Math.round(value.max / 5) * 5 + 5;
					}
				},
				series: series
			};
			echart.value.setOption(option);
		} else {
			ElMessage.error('暂无数据');
		}
	} catch (error) {
		console.error(error);
	} finally {
		loading.value = false;
	}
}

const downloadUrlFile = (url: any, fileName: any) => {
	const a = document.createElement('a');
	document.body.appendChild(a);
	a.style = 'display: none';
	a.href = url;
	if (fileName) {
		a.download = fileName;
	}
	a.click();
	window.URL.revokeObjectURL(url);
}

const downloadChart = () => {
	const chartImgUrl = echart.value.getDataURL({
		pixelRatio: 2,
		backgroundColor: '#ffffff'
	});
	downloadUrlFile(chartImgUrl, `供暖分析${route.query.queryTime}`);
}
</script>

<style lang='scss' scoped>
.home-view {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100%;
	width: 100%;

	.download {
		position: absolute;
		top: 50px;
		right: 180px;
	}

	.export{
		position: absolute;
		top: 50px;
		right: 80px;
	}

	.echart {
		height: 80%;
		width: 80%;
	}
}
</style>
